<template>
  <view class="product-edit-container">
    <view class="page-header">
      <text class="page-title">编辑产品</text>
      <text class="page-subtitle">修改产品信息</text>
    </view>

    <view v-if="pageLoading" class="page-loading-container">
      <view class="loading-spinner"></view>
      <text class="loading-text">加载数据中...</text>
    </view>

    <view v-else class="form-container">
      <view class="form-section">
        <text class="section-title">基本信息</text>
        
        <view class="form-item">
          <text class="form-label required">产品名称</text>
          <uni-easyinput 
            v-model="formData.product_name"
            placeholder="请输入产品名称"
            :maxlength="100"
            :clearable="true"
            trim="all"
          />
          <text v-if="errors.product_name" class="error-text">{{ errors.product_name }}</text>
        </view>

        <view class="form-item">
          <text class="form-label">产品代码</text>
          <uni-easyinput 
            v-model="formData.product_code"
            placeholder="请输入产品代码"
            :clearable="true"
            trim="all"
          />
        </view>

        <view class="form-item">
          <text class="form-label required">产品类型</text>
          <radio-group @change="onProductTypeChange" class="radio-group">
            <label class="radio-item">
              <radio value="1" :checked="formData.product_type === 1" color="#007aff"/>
              <text class="radio-text">药品</text>
            </label>
            <label class="radio-item">
              <radio value="2" :checked="formData.product_type === 2" color="#007aff"/>
              <text class="radio-text">医疗器材</text>
            </label>
            <label class="radio-item">
              <radio value="3" :checked="formData.product_type === 3" color="#007aff"/>
              <text class="radio-text">其他</text>
            </label>
          </radio-group>
        </view>

        <view class="form-item">
          <text class="form-label">产品描述</text>
          <textarea 
            v-model="formData.description" 
            class="form-textarea" 
            placeholder="请输入产品描述"
            maxlength="500"
          />
        </view>

        <view class="form-item">
          <text class="form-label">产品图片</text>
          <uni-file-picker 
            v-model="imageFileList"
            file-mediatype="image"
            mode="grid"
            :limit="1"
            :auto-upload="false"
            @select="handleImageSelect"
            @delete="handleImageDelete"
          />
        </view>
      </view>

      <view class="form-section">
        <text class="section-title">价格与库存</text>
        
        <view class="form-item">
          <text class="form-label required">价格（元）</text>
          <uni-easyinput 
            v-model="formData.price"
            type="number"
            placeholder="请输入产品价格"
            :clearable="true"
          />
          <text v-if="errors.price" class="error-text">{{ errors.price }}</text>
        </view>

        <view class="form-item">
          <text class="form-label">库存数量</text>
          <uni-easyinput 
            v-model="formData.stock_quantity"
            type="number"
            placeholder="请输入库存数量"
            :clearable="true"
          />
        </view>

        <view class="form-item">
          <text class="form-label">库存预警阈值</text>
          <uni-easyinput 
            v-model="formData.stock_alert_threshold"
            type="number"
            placeholder="请输入预警阈值"
            :clearable="true"
          />
        </view>
      </view>

      <view class="form-section">
        <text class="section-title">供应商信息</text>
        
        <view class="form-item">
          <text class="form-label">供应商</text>
          <uni-easyinput 
            v-model="formData.supplier"
            placeholder="请输入供应商名称"
            :clearable="true"
            trim="all"
          />
        </view>

        <view class="form-item">
          <text class="form-label">批号</text>
          <uni-easyinput 
            v-model="formData.batch_no"
            placeholder="请输入产品批号"
            :clearable="true"
            trim="all"
          />
        </view>

        <view class="form-item">
          <text class="form-label">过期日期</text>
          <picker mode="date" :value="formData.expiry_date" @change="onExpiryDateChange">
            <view class="picker-view">
              <text class="picker-text">{{ formData.expiry_date || '请选择过期日期' }}</text>
            </view>
          </picker>
        </view>
      </view>

      <view class="form-section">
        <text class="section-title">其他信息</text>
        
        <view class="form-item">
          <text class="form-label required">状态</text>
          <radio-group @change="onStatusChange" class="radio-group">
            <label class="radio-item">
              <radio value="1" :checked="formData.status === 1" color="#007aff"/>
              <text class="radio-text">在售</text>
            </label>
            <label class="radio-item">
              <radio value="2" :checked="formData.status === 2" color="#007aff"/>
              <text class="radio-text">停售</text>
            </label>
            <label class="radio-item">
              <radio value="3" :checked="formData.status === 3" color="#007aff"/>
              <text class="radio-text">禁用</text>
            </label>
          </radio-group>
        </view>
      </view>

      <view class="form-actions">
        <button class="btn btn-cancel" @click="handleCancel">取消</button>
        <button class="btn btn-primary" @click="handleSubmit">保存</button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'

const pageLoading = ref(true)
const productId = ref('')
const imageFileList = ref([])
const originalImageUrl = ref('')
const originalImageData = ref(null) // 保存原始image对象

const formData = reactive({
  product_name: '',
  product_code: '',
  product_type: 1,
  description: '',
  image: '',
  price: '',
  stock_quantity: '',
  stock_alert_threshold: '',
  supplier: '',
  batch_no: '',
  expiry_date: '',
  status: 1
})

const errors = reactive({
  product_name: '',
  price: ''
})

onMounted(async () => {
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  productId.value = currentPage.options.id || ''
  
  if (!productId.value) {
    uni.showToast({ title: '缺少产品ID', icon: 'none' })
    setTimeout(() => {
      uni.redirectTo({ url: '/pages/business/products/list' })
    }, 1500)
    return
  }
  
  await loadProductData()
  pageLoading.value = false
})

function getImageUrl(imageData) {
  if (!imageData) return ''
  if (typeof imageData === 'string') return imageData
  if (typeof imageData === 'object' && imageData.url) return imageData.url
  if (Array.isArray(imageData) && imageData.length > 0) {
    const first = imageData[0]
    return typeof first === 'string' ? first : (first.url || '')
  }
  return ''
}

async function loadProductData() {
  try {
    // 调用云对象方法获取产品信息
    const productsObj = uniCloud.importObject('dh-products')
    const result = await productsObj.getProductById(productId.value)
    
    if (result.code === 200 && result.data) {
      const data = result.data
      
      let expiryDateStr = ''
      if (data.expiry_date) {
        const date = new Date(data.expiry_date)
        const year = date.getFullYear()
        const month = String(date.getMonth() + 1).padStart(2, '0')
        const day = String(date.getDate()).padStart(2, '0')
        expiryDateStr = `${year}-${month}-${day}`
      }
      
      // 保存原始图片数据（确保是file对象格式）
      if (data.image) {
        if (typeof data.image === 'string') {
          // 如果是字符串URL，转换为file对象
          originalImageData.value = {
            bsonType: 'file',
            fileMediaType: 'image',
            url: data.image
          }
        } else {
          // 如果已经是对象，直接保存
          originalImageData.value = data.image
        }
      } else {
        originalImageData.value = null
      }
      
      const imageUrl = getImageUrl(data.image)
      
      Object.assign(formData, {
        product_name: data.product_name || '',
        product_code: data.product_code || '',
        product_type: data.product_type || 1,
        description: data.description || '',
        image: imageUrl,
        price: data.price?.toString() || '',
        stock_quantity: data.stock_quantity?.toString() || '',
        stock_alert_threshold: data.stock_alert_threshold?.toString() || '',
        supplier: data.supplier || '',
        batch_no: data.batch_no || '',
        expiry_date: expiryDateStr,
        status: data.status || 1
      })
      
      if (imageUrl) {
        originalImageUrl.value = imageUrl
        imageFileList.value = [{ url: imageUrl, name: '产品图片' }]
      }
    } else {
      throw new Error(result.message || '产品不存在')
    }
  } catch (err) {
    uni.showToast({ title: err.message || '加载失败', icon: 'none' })
    setTimeout(() => {
      uni.redirectTo({ url: '/pages/business/products/list' })
    }, 1500)
  }
}

function onProductTypeChange(e) {
  formData.product_type = parseInt(e.detail.value)
}

function onStatusChange(e) {
  formData.status = parseInt(e.detail.value)
}

function onExpiryDateChange(e) {
  formData.expiry_date = e.detail.value
}

function handleImageSelect(e) {
  if (e.tempFiles && e.tempFiles.length > 0) {
    imageFileList.value = e.tempFiles
  }
}

function handleImageDelete(e) {
  imageFileList.value = []
}

async function uploadImageToCloud() {
  if (!imageFileList.value || imageFileList.value.length === 0) {
    return null
  }
  
  try {
    const tempFile = imageFileList.value[0]
    const uploadResult = await uniCloud.uploadFile({
      filePath: tempFile.path,
      cloudPath: `products/${Date.now()}_${Math.random().toString(36).substr(2, 9)}.${tempFile.name.split('.').pop()}`
    })
    // 返回符合数据库schema的file对象结构
    return {
      name: uploadResult.fileID.split('/').pop(),
      extname: tempFile.name.split('.').pop(),
      url: uploadResult.fileID,
      size: tempFile.size || 0,
      file_id: uploadResult.fileID
    }
  } catch (err) {
    throw err
  }
}

function validateForm() {
  let isValid = true
  
  if (!formData.product_name || formData.product_name.trim().length === 0) {
    errors.product_name = '请输入产品名称'
    isValid = false
  } else {
    errors.product_name = ''
  }
  
  if (!formData.price || parseFloat(formData.price) <= 0) {
    errors.price = '请输入有效的产品价格'
    isValid = false
  } else {
    errors.price = ''
  }
  
  return isValid
}

async function handleSubmit() {
  if (!validateForm()) {
    uni.showToast({ title: '请检查表单错误', icon: 'none' })
    return
  }
  
  try {
    uni.showLoading({ title: '保存中...' })
    
    // 处理图片
    let imageData = null
    const hasNewImage = imageFileList.value && 
                        imageFileList.value.length > 0 && 
                        imageFileList.value[0].path && 
                        !imageFileList.value[0].url
    
    if (hasNewImage) {
      try {
        uni.showLoading({ title: '上传图片中...' })
        imageData = await uploadImageToCloud()
      } catch (uploadErr) {
        uni.hideLoading()
        uni.showToast({ 
          title: '图片上传失败：' + (uploadErr.message || '未知错误'), 
          icon: 'none'
        })
        return
      }
    } else if (originalImageData.value) {
      // 保持原始file对象格式
      imageData = originalImageData.value
    }
    
    const db = uniCloud.database()
    const dbCmd = db.command
    
    // 构建提交数据（hospital_id将由云函数自动添加）
    const submitData = {
      product_name: formData.product_name,
      product_code: formData.product_code,
      product_type: formData.product_type,
      description: formData.description,
      price: parseFloat(formData.price) || 0,
      stock_quantity: parseInt(formData.stock_quantity) || 0,
      stock_alert_threshold: parseInt(formData.stock_alert_threshold) || 0,
      supplier: formData.supplier,
      batch_no: formData.batch_no,
      expiry_date: formData.expiry_date ? new Date(formData.expiry_date).getTime() : null,
      status: formData.status,
      update_time: Date.now()
    }
    
    // 处理图片字段
    if (imageData) {
      submitData.image = imageData
    } else {
      submitData.image = dbCmd.remove()
    }
    
    // 调用云对象方法更新产品信息
    const productsObj = uniCloud.importObject('dh-products')
    const result = await productsObj.updateProduct(productId.value, submitData)
    
    uni.hideLoading()
    
    if (result.code === 200) {
      uni.showToast({ title: result.message || '更新成功', icon: 'success' })
      setTimeout(() => {
        uni.redirectTo({ url: '/pages/business/products/list' })
      }, 1500)
    } else {
      uni.showToast({ title: '更新失败', icon: 'none' })
    }
  } catch (err) {
    uni.hideLoading()
    uni.showToast({ title: err.message || '更新失败', icon: 'none' })
  }
}

function handleCancel() {
  uni.redirectTo({ url: '/pages/business/products/list' })
}
</script>

<style lang="scss" scoped>
.product-edit-container {
  min-height: 100vh;
  background: #f5f5f5;
  padding: 20rpx;
}

.page-header {
  background: #fff;
  padding: 40rpx;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);
}

.page-title {
  font-size: 44rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 12rpx;
}

.page-subtitle {
  font-size: 28rpx;
  color: #999;
  display: block;
}

.page-loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 200rpx 0;
  background: #fff;
  border-radius: 16rpx;
}

.loading-spinner {
  width: 80rpx;
  height: 80rpx;
  border: 6rpx solid #f3f3f3;
  border-top: 6rpx solid #007aff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 30rpx;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-text {
  font-size: 28rpx;
  color: #666;
}

.form-container {
  background: #fff;
  border-radius: 16rpx;
  overflow: hidden;
}

.form-section {
  padding: 40rpx;
  border-bottom: 1rpx solid #f0f0f0;
  
  &:last-child {
    border-bottom: none;
  }
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 30rpx;
  padding-bottom: 16rpx;
  border-bottom: 2rpx solid #007aff;
}

.form-item {
  margin-bottom: 32rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.form-label {
  font-size: 28rpx;
  color: #666;
  display: block;
  margin-bottom: 16rpx;
  
  &.required::after {
    content: ' *';
    color: #ff3b30;
  }
}

.form-textarea {
  width: 100%;
  min-height: 160rpx;
  padding: 20rpx;
  font-size: 28rpx;
  border: 1rpx solid #e0e0e0;
  border-radius: 8rpx;
  box-sizing: border-box;
  background: #fafafa;
}

.picker-view {
  padding: 20rpx;
  background: #fafafa;
  border: 1rpx solid #e0e0e0;
  border-radius: 8rpx;
}

.picker-text {
  font-size: 28rpx;
  color: #333;
}

.radio-group {
  display: flex;
  flex-wrap: wrap;
  gap: 24rpx;
}

.radio-item {
  display: flex;
  align-items: center;
  padding: 16rpx 24rpx;
  background: #fafafa;
  border-radius: 8rpx;
  border: 1rpx solid #e0e0e0;
}

.radio-text {
  font-size: 28rpx;
  color: #333;
  margin-left: 12rpx;
}

.error-text {
  font-size: 24rpx;
  color: #ff3b30;
  display: block;
  margin-top: 8rpx;
}

.form-actions {
  display: flex;
  gap: 20rpx;
  padding: 30rpx 40rpx;
  background: #fff;
  border-top: 1rpx solid #f0f0f0;
}

.btn {
  flex: 1;
  height: 88rpx;
  line-height: 88rpx;
  text-align: center;
  font-size: 32rpx;
  border-radius: 12rpx;
  border: none;
  
  &.btn-cancel {
    background: #f5f5f5;
    color: #666;
  }
  
  &.btn-primary {
    background: #007aff;
    color: #fff;
  }
}
</style>
